// 1: 导入axios异步请求组件
import axios from "axios";
// 2: 把axios请求的配置剥离成一个config/index.js的文件
import {api} from "./config";
// 4: elementplus消息框
import KVA from "@/utils/kva.js";
// 5: 获取登录的token信息
import {useUserStore} from '@/stores/users.js'
// 6: 然后创建一个axios的实例
const request = axios.create({...api})

// request request请求拦截器
request.interceptors.request.use(
    function (config) {
        const userStore = useUserStore()
        if(!config.noToken) {
            const currentSystem = userStore.systemList?.filter(c => c.defaultFlag == 1)[0]
            config.headers.SystemId = currentSystem?.id
            config.headers.MaYa = "maya"
            config.headers.Uid = userStore.userId
            config.headers.Authorization = userStore.getToken()
        }
        // 这个判断就是为了那些不需要token接口做开关处理，比如：登录，检测等
        if (config.method === 'post') {
            if (config.contentType === 1) {
                config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
            } else if (config.contentType === 2) {
                config.headers['Content-Type'] = 'multipart/form-data'
            } else {
                config.headers['Content-Type'] = 'application/json;charset=utf-8' // 数组
            }
        }
        return config;
    }, function (error) {
        // 判断请求超时
        if (error.code === "ECONNABORTED" && error.message.indexOf("timeout") !== -1) {
            KVA.notifyError('请求超时');
            // 这里为啥不写return
        }
        return Promise.reject(error);
    }
);

// request response 响应拦截器
request.interceptors.response.use((response) => {
    // 如果是文件上传的类型，直接返回
    if(response.config.responseType === 'blob'){
        return response
    }else {
        const userStore = useUserStore()
        if (response.data.code === 40004) {
            userStore.logout()
            return
        }

        if (response.data.code === 50004) {
            KVA.notifyError(response.data.message);
            userStore.logout()
            return
        }

        //后端返回非200和20000状态码，前端弹出错误提示
        if (response.data.code && response.data.code !== 200 && response.data.code !== 20000) {
            KVA.notifyError(response.data.desc || response.data.message);
            return Promise.reject(response.data);
        }

        // 开始续期
        if (response.headers["new-token"]) {
            const userStore = useUserStore()
            userStore.setToken(response.headers["new-token"])
        }

        if (response.data.code === 20000) {
            return response.data;
        } else {
            if (response.data.message) {
                KVA.notifyError(response.data.message);
            }
            // 返回接口返回的错误信息
            return Promise.reject(response.data);
        }
    }
}, (err) => {
    if (err && err.response) {
        switch (err.response.status) {
            case 400:
                err.message = "请求错误";
                break;
            case 401:
                err.message = "未授权，请登录";
                break;
            case 403:
                err.message = "拒绝访问";
                break;
            case 404:
                err.message = `请求地址出错: ${err.response.config.url}`;
                break;
            case 408:
                err.message = "请求超时";
                break;
            case 500:
                err.message = "服务器内部错误";
                break;
            case 501:
                err.message = "服务未实现";
                break;
            case 502:
                err.message = "网关错误";
                break;
            case 503:
                err.message = "服务不可用";
                break;
            case 504:
                err.message = "网关超时";
                break;
            case 505:
                err.message = "HTTP版本不受支持";
                break;
            default:
        }
    }
    if (err.message) {
        KVA.notifyError(err.message);
    }
    // 判断请求超时
    if (err.code === "ECONNABORTED" && err.message.indexOf("timeout") !== -1) {
        KVA.notifyError('服务已经离开地球表面，刷新或者重试...');
    }
    // 返回接口返回的错误信息
    return Promise.reject(err);
})

export default request
